package com.niiwoo.civet.trade.service.dubbo.loan;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.activity.stage.dto.request.prize.ActivityPrizeResetStatusReqDTO;
import com.niiwoo.activity.stage.service.prize.ActivityPrizeDubboService;
import com.niiwoo.civet.trade.dao.entity.ProjectBackoutBorrowPrize;
import com.niiwoo.civet.trade.service.loan.ProjectBackoutBorrowPrizeDubboService;
import com.niiwoo.civet.trade.service.local.loan.ProjectBackoutBorrowPrizeService;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Service(version = "1.0.0")
@Slf4j
public class ProjectBackoutBorrowPrizeDubboServiceImpl implements ProjectBackoutBorrowPrizeDubboService {

    @Autowired
    ProjectBackoutBorrowPrizeService projectBackoutBorrowPrizeService;

    @Reference(version = "1.0.0")
    ActivityPrizeDubboService activityPrizeDubboService;

    @Override
    public void backAll() {
        Optional.ofNullable(projectBackoutBorrowPrizeService.getAllNotBack())
                .filter(list -> !list.isEmpty())
                .ifPresent(list -> list.forEach(prize -> {
                    ActivityPrizeResetStatusReqDTO reqDTO = new ActivityPrizeResetStatusReqDTO();
                    reqDTO.setPrizeId(prize.getPrizeId());
                    reqDTO.setUserId(prize.getUserId());
                    log.info("退回借款红包计划任务###请求, projectId={}, request={}", prize.getProjectId(), JSON.toJSONString(reqDTO));
                    try {
                        activityPrizeDubboService.resetPrizeToReturned(reqDTO);
                        log.info("退回借款红包计划任务###成功, 删除退回记录, projectId={}, prizeId={}", prize.getProjectId(), prize.getPrizeId());
                        projectBackoutBorrowPrizeService.del(prize.getProjectId());
                    } catch (Exception e) {
                        log.error(String.format("退回借款红包计划任务###异常, projectId=%s, prizeId=%s, errorMessage=%s", prize.getProjectId(), prize.getPrizeId() , e.getMessage()), e);
                    }
                }));

    }

}
